package com.gingko.duominuo.utils

import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import android.widget.Toast
import androidx.annotation.StringRes
import com.gingko.duominuo.App
import com.gingko.duominuo.R

/**
 * Describe：
 * -
 *
 * @author bsx
 * CreateTime：2019/11/8
 */

fun Any.toast(duration: Int = Toast.LENGTH_SHORT) {
    if (this is CharSequence) {
        ToastUtils.show(this, duration)
    } else {
        ToastUtils.show(this.toString(), duration)
    }
}


object ToastUtils {
    //    private val mToast: Toast by lazy {
//        Toast(BaseApp.instance).also {
//            it.setGravity(Gravity.CENTER, 0, 0)
//            val inflater = LayoutInflater.from(BaseApp.instance)
//            val view: View = inflater.inflate(R.layout.layout_toast, null)
//            it.view = view
//        }
//    }
//
//    private val tvToast: TextView by lazy {
//        mToast.view.findViewById<TextView>(R.id.tv_toast)
//    }
//    private var tvToast: TextView? = null
    private var mToast: Toast? = null


    @JvmStatic
    fun show(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
        showCustomToast(message.toString(), duration)
    }

    @JvmStatic
    fun showShort(@StringRes message: Int) {
        show(App.instance.getString(message), Toast.LENGTH_SHORT)
    }

    @JvmStatic
    fun showShort(message: CharSequence) {
        show(message.toString(), Toast.LENGTH_SHORT)
    }

    @JvmStatic
    fun showLong(message: CharSequence) {
        show(message.toString(), Toast.LENGTH_LONG)
    }

    /**
     * 自定义toast
     *
     * @param context  application
     * @param message  显示内容
     * @param duration 显示时长
     */
    private fun showCustomToast(message: CharSequence, duration: Int = Toast.LENGTH_SHORT) {
        mToast?.cancel()
        mToast = Toast(App.instance).also {
            it.setGravity(Gravity.CENTER, 0, 0)
            it.duration = duration
            val inflater = LayoutInflater.from(App.instance)
            val view: View = inflater.inflate(R.layout.layout_toast, null)
            val tvToast = view.findViewById<TextView>(R.id.tv_toast)
            tvToast.text = message
            it.view = view
            it.show()
        }


    }

}